<template>
  <div>
    <div style="margin-bottom: 5px">
      <el-input v-model="userName"  placeholder="请输入名字" suffix-icon="el-icon-search" style="width: 300px"
                @keyup.enter.native="loadPost"></el-input>
      <el-button style="margin-left: 5px" type="primary" icon="el-icon-search" @click="loadPost">查询</el-button>
      <el-button style="margin-left: 5px" type="success" icon='el-icon-refresh-left' @click="reset">重置</el-button>
      <el-button style="margin-left: 5px" type="warning" icon='el-icon-circle-plus-outline' @click="add">新增</el-button>
    </div>
    <el-table :data="tableData" style="width: 100%"
              :header-cell-style="{background: '#f3f6fd', color: '#211e1e'}"

    >
      <el-table-column prop="userId" label="ID" min-width="40%" align="center">
      </el-table-column>
      <el-table-column prop="userNum" label="账号" min-width="100%" align="center">
      </el-table-column>
      <el-table-column prop="userName" label="姓名" min-width="100%" align="center">
      </el-table-column>
      <el-table-column prop="userAge" label="年龄" min-width="40%" align="center">
      </el-table-column>
      <el-table-column prop="userSex" label="性别" min-width="60%" align="center">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.userSex === 1 ? 'primary' : 'success'"
              disable-transitions>{{scope.row.userSex === 1 ? '男' : '女'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="roleId" label="角色" min-width="100%" align="center">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.roleId === 0 ?'danger' :(scope.row.roleId === 1 ?'warning' : 'info')"
              disable-transitions>{{scope.row.roleId === 0 ? '超级管理员' : (scope.row.roleId === 1 ? '社团管理员' : '社团成员')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="cname" label="所属社团" min-width="100%" align="center">
      </el-table-column>
      <el-table-column prop="userPhone" label="电话" min-width="100%" align="center">
      </el-table-column>
      <el-table-column prop="operate" label="操作" min-width="80%" align="center">
        <template v-slot="scope">
          <el-button type="text" icon="el-icon-edit" size="medium" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗？"
              @confirm="del(scope.row.userId)"
              style="margin-left: 5px"
          >
            <el-button slot="reference" type="text" icon="el-icon-delete" size="medium" >删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>

    <el-dialog
        title="提示"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="账号" prop="userNum">
          <el-col :span="20">
            <el-input v-model="form.userNum" :disabled="disabled_index"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="名字" prop="userName">
          <el-col :span="20">
            <el-input v-model="form.userName" ></el-input>
          </el-col>
        </el-form-item>

        <el-form-item label="密码" prop="userPassword" >
          <el-col :span="20">
            <el-input v-model="form.userPassword" type="password"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="年龄" prop="userAge">
          <el-col :span="20">
            <el-input v-model="form.userAge" ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="性别" prop="userSex">
          <el-radio-group v-model="form.userSex">
            <el-radio label="1">男</el-radio>
            <el-radio label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="电话" prop="userPhone">
          <el-col :span="20">
            <el-input v-model="form.userPhone" ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" >
    <el-button @click="centerDialogVisible=false">取 消</el-button>
    <el-button type="primary" @click="save">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  name: "AdminManage",
  components: {
  },
  data(){
    let checkAge = (rule, value, callback) => {
      if(value>150){
        callback(new Error('年龄输入过大'));
      }else{
        callback();
      }
    };
    let checkDuplicate =(rule,value,callback)=>{
      if(this.form.userId){
        return callback();
      }
      this.$axios.get(this.$httpUrl+"/user/findByNo?userNum="+this.form.userNum).then(res=>res.data).then(res=>{
        if(res.code!=200){
          callback()
        }else{
          callback(new Error('账号已经存在'));
        }
      })
    };
    return {
      user: JSON.parse(sessionStorage.getItem('CurUser')),
      disabled_index:false,
      tableData: [],
      cNameData:[],
      pageSize:10,
      pageNum:1,
      total:0,
      userName:'',
      LastPassword:'',
      roleId:'',
      cId:'',
      centerDialogVisible:false,
      form:{
        userId:'',
        userName:'',
        userNum:'',
        userPassword:'',
        userAge:'',
        userPhone:'',
        userSex:'0',
        cid:'',
        roleId:'2'
      },
      rules:{
        userNum: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { min: 5, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' },
          {validator:checkDuplicate,trigger: 'blur'}
        ],
        userName: [
          { required: true, message: '请输入名字', trigger: 'blur' },
        ],
        userPassword: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 36, message: '长度在 6 到 36 个字符', trigger: 'blur' }
        ],
        userAge: [
          {required: true, message: '请输入年龄', trigger: 'blur'},
          {min: 1, max: 3, message: '⻓度在 1 到 3 个位', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,3}$/,message: '年龄必须为正整数字',trigger: "blur"},
          {validator:checkAge,trigger: 'blur'}
        ],
        userPhone: [
          {required: true,message: "手机号不能为空",trigger: "blur"},
          {pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur"}
        ]
      }
    }
  },
  created() {
    // this.loadGet();
    this.loadPost();
    this.loadCname();
  },
  methods:{
    loadCname(){
      this.$axios.get(this.$httpUrl+'/community/list').then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.cNameData=res.data
        }else{
          alert("获取数据失败")
        }
      })
    },
    resetForm(){
      this.$refs.form.resetFields();
    },
    mod(row){
      console.log(row)
      this.centerDialogVisible=true
      this.$nextTick(()=>{
        this.form.userId = row.userId
        this.form.userNum = row.userNum
        this.form.userName = row.userName
        this.form.userPassword = row.userPassword
        this.LastPassword = row.userPassword
        this.form.userAge = row.userAge+''
        this.form.userSex = row.userSex+''
        this.form.userPhone = row.userPhone
        this.form.roleId = row.roleId
        this.form.cid = row.cid
        this.disabled_index = true
      })

    },
    del(userId){
      console.log(userId)
      this.$axios.get(this.$httpUrl+'/user/delete?userId='+userId).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          this.centerDialogVisible=false
          this.loadPost()
        }else{
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'error'
          });
        }
      })
    },
    loadGet(){
      this.$axios.get(this.$httpUrl+'/user/list').then(res=>res.data).then(res=>{
        console.log(res)
      })
    },
    loadPost(){
      this.$axios.post(this.$httpUrl+'/user/listPage1',{
        pageSize:this.pageSize,
        pageNum:this.pageNum,
        params:{
          userName:this.userName,
          cId: this.user.cid+''
        }
      }).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.tableData=res.data
          this.total=res.total
        }else{
          alert("获取数据失败")
        }
      })
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum=1
      this.pageSize=val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum=val
      this.loadPost()
    },
    reset(){
      this.userName=''
      this.roleId=''
      this.cId=''
      this.loadPost()
    },
    doMod(){
      if (this.LastPassword != this.form.userPassword) {
        this.form.userPassword = this.$md5(this.form.userPassword)
      }
      this.$axios.post(this.$httpUrl+'/user/update',this.form).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          this.centerDialogVisible=false
          this.loadPost()
        }else{
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'error'
          });
        }
      })
    },
    dosave(){
      this.form.userPassword = this.$md5(this.form.userPassword)
      this.$axios.post(this.$httpUrl+'/user/add',this.form).then(res=>res.data).then(res=>{
        console.log(res)
        if (res.code==200){
          this.$message({
            showClose: true,
            message: '操作成功',
            type: 'success'
          });
          this.centerDialogVisible=false
          this.loadPost()
        }else{
          this.$message({
            showClose: true,
            message: '操作失败',
            type: 'error'
          });
        }
      })
    },
    save(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.form.cid = this.user.cid
          if (this.form.userId == ''){
            console.log("新增")
            this.dosave();
          }else{
            console.log("修改")
            this.doMod();
            this.form.userId = ''
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    add(){

      this.centerDialogVisible=true
      this.disabled_index = false
      this.$nextTick(()=>{
        this.resetForm()
      })
    }
  }
}
</script>

<style scoped>

</style>